package com.hxb.example.util;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.Request;
import com.microsoft.playwright.Response;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;

@Slf4j
public class PlayWrightUtil {

    public static BrowserContext createContext(Browser browser) {
        return browser.newContext(new Browser.NewContextOptions()
                .setIgnoreHTTPSErrors(true)
                .setJavaScriptEnabled(true)
                .setViewportSize(1920, 1080)
                .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36"));
    }


    public static Browser createBrowser(String name, Playwright playwright) {
        try {
            switch (name) {
                case "firefox":
                    return playwright.firefox().launch();
                case "chromium":
                    return playwright.chromium()
                            .launch(new BrowserType.LaunchOptions()
                                    .setChannel("chromium")
                                    .setHeadless(false)
                                    .setTimeout(120 * 1000));
                case "webkit":
                    return playwright.webkit().launch();
            }
        } catch (Exception e) {
            throw new RuntimeException("browser创建失败");
        }
        return playwright.webkit().launch();
    }

    public static Page initDefaultPage() {
        return initPage("chromium");
    }

    public static Page initPage(String browserName) {
        Playwright playwright = Playwright.create();
        Browser browser = createBrowser(browserName, playwright);
        // BrowserContext browserContext = createContext(browser);
        return browser.newPage();
    }

    public static void handleOn(Page page, Consumer<Request> requestConsumer, Consumer<Response> responseConsumer) {
        page.onRequest(requestConsumer);
        page.onResponse(responseConsumer);
    }

    public static void handleOn(String url, Consumer<Request> requestConsumer, Consumer<Response> responseConsumer) {
        try (Page page = initDefaultPage()) {
            page.navigate(url);
            page.onRequest(requestConsumer);
            page.onResponse(responseConsumer);
        } catch (Exception e) {
            log.error("抓取数据失败", e);
        }
    }


}
